/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package biojavagoalz.worker;

import java.util.LinkedList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Manages workers and holds work that is later distributed
 * @author Tadas
 */
public class WorkManager {

    private LinkedList<StringWorker> workers = new LinkedList<StringWorker>();
    private LinkedBlockingQueue<Item> items = new LinkedBlockingQueue<Item>(100);
    private LinkedBlockingQueue<String> results = new LinkedBlockingQueue<String>(100);
    int indexCount = 0;
    int workersActive = 0;

    public void putItem(Item item) {
        try {
            items.offer(item, 10, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            throw new RuntimeException("Failed to add item");
        }
    }

    public void addWorker(StringWorker worker) {
        workers.add(worker);
        workersActive++;
        worker.start();
    }

    synchronized void finishedWork(){
        workersActive--;
    }

    public int getActiveWorkers(){
        return workersActive;
    }

    public Item getItem() {
        try {
            return items.poll(1, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
        }
        return null;
    }

    synchronized public void putResult(String rez) {
        try {
            results.offer(rez, 10, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            throw new RuntimeException("Cannot put more results");
        }
        indexCount++;
    }

    public BlockingQueue<String> getResults() {
        return results;
    }

    public int getIndexCount() {
        return indexCount;
    }
}
